package com.ele.client.activity.auth;

import com.ele.client.ClientFactory;
import com.ele.client.activity.home.HomePlace;
import com.ele.client.rpc.SimpleAsyncCallback;
import com.ele.client.util.UserHelper;
import com.ele.model.AppUser;
import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.Place;
import com.google.gwt.user.client.ui.AcceptsOneWidget;

public class LoginActivity extends AbstractActivity implements LoginView.Presenter {

    private ClientFactory clientFactory;
    private String email;
    private LoginView view;

    public LoginActivity(LoginPlace place, ClientFactory clientFactory) {
        this.clientFactory = clientFactory;
        this.email = place.getEmail();
    }

    @Override
    public void start(AcceptsOneWidget container, EventBus eventBus) {
        view = clientFactory.getLoginView();
        view.setEmail(email);
        view.setPresenter(this);
        container.setWidget(view.asWidget());
    }

    @Override
    public void login(String email, String password) {
        view.startLoading();

        clientFactory.getApplicationService().login(email, password, new SimpleAsyncCallback<AppUser>() {
            @Override
            public void onSuccess(AppUser user) {
                boolean successful = user != null;

                if (successful) {
                    UserHelper.setUser(user);
                    Place referrer = UserHelper.getReferrer();
                    Place place = referrer == null ? new HomePlace() : referrer;
                    clientFactory.getPlaceController().goTo(place);
                } else {
                    view.showAlert();
                }
                view.stopLoading();
            }
        });
    }

    @Override
    public void goToRegister(String email) {
        clientFactory.getPlaceController().goTo(new RegistrationPlace(email));
    }
}
